package org.jeecgframework.web.controller;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.jeecgframework.core.common.model.json.ComboTree;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.vo.easyui.ComboTreeModel;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;

import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.web.util.FileBean;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.jeecgframework.web.util.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;

import java.io.OutputStream;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 技术支持完工单
 * @date 2018-03-20 17:01:39
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsTechologyAgreeReportController")
public class CbsTechologyAgreeReportController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsTechologyAgreeReportController.class);

    @Autowired
    private CbsTechologyAgreeReportServiceI cbsTechologyAgreeReportService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    CbsServiceReportServiceI cbsServiceReportService;
    private String message;
    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;
    @Autowired
    private CbsServiceErrorLogServiceI cbsServiceErrorLogService;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 技术支持完工单列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsTechologyAgreeReport")
    public ModelAndView cbsTechologyAgreeReport(HttpServletRequest request) {
        return new ModelAndView("com/zybk/org.jeecgframework/cbsTechologyAgreeReportList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(CbsTechologyAgreeReportEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsTechologyAgreeReport, request.getParameterMap());
        try {
            //自定义追加查询条件
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
        cq.add();
        this.cbsTechologyAgreeReportService.getDataGridReturn(cq, true);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 根据code值获取市
     */
    @RequestMapping(params = "getCityByCode")
    @ResponseBody
    public AjaxJson getCityByCode(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String code = request.getParameter("province");
            String hql = "from TSTerritory where territoryLevel = 2 and TSTerritory.territoryCode = '" + code + "' ";
            List<TSTerritory> territoryList = systemService.findHql(hql);
            ajaxJson.setObj(territoryList);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }


    /**
     * 技术支持完工单新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsTechologyAgreeReport.getId())) {
            cbsTechologyAgreeReport = cbsTechologyAgreeReportService.getEntity(CbsTechologyAgreeReportEntity.class, cbsTechologyAgreeReport.getId());
            req.setAttribute("cbsTechologyAgreeReportPage", cbsTechologyAgreeReport);
        }
        return new ModelAndView("com/zybk/org.jeecgframework/cbsTechologyAgreeReport-add");
    }


    /**
     * 添加技术支持完工单
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "技术支持完工单添加成功";
        try {
            cbsTechologyAgreeReportService.save(cbsTechologyAgreeReport);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "技术支持完工单添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 技术支持完工单编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(cbsTechologyAgreeReport.getId())) {
            cbsTechologyAgreeReport = cbsTechologyAgreeReportService.getEntity(CbsTechologyAgreeReportEntity.class, cbsTechologyAgreeReport.getId());
            req.setAttribute("cbsTechologyAgreeReportPage", cbsTechologyAgreeReport);
        }
        return new ModelAndView("com/zybk/org.jeecgframework/cbsTechologyAgreeReport-update");
    }

    /**
     * 更新技术支持完工单
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "技术支持完工单更新成功";
        CbsTechologyAgreeReportEntity t = cbsTechologyAgreeReportService.get(CbsTechologyAgreeReportEntity.class, cbsTechologyAgreeReport.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(cbsTechologyAgreeReport, t);
            cbsTechologyAgreeReportService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "技术支持完工单更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 删除技术支持完工单
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsTechologyAgreeReport = systemService.getEntity(CbsTechologyAgreeReportEntity.class, cbsTechologyAgreeReport.getId());
        message = "技术支持完工单删除成功";
        try {
            cbsTechologyAgreeReportService.delete(cbsTechologyAgreeReport);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "技术支持完工单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除技术支持完工单
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "技术支持完工单删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsTechologyAgreeReportEntity cbsTechologyAgreeReport = systemService.getEntity(CbsTechologyAgreeReportEntity.class,
                        id
                );
                cbsTechologyAgreeReportService.delete(cbsTechologyAgreeReport);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "技术支持完工单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/org.jeecgframework/cbsTechologyAgreeReportUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsTechologyAgreeReportEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsTechologyAgreeReport, request.getParameterMap());
        List<CbsTechologyAgreeReportEntity> cbsTechologyAgreeReports = this.cbsTechologyAgreeReportService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "技术支持完工单");
        modelMap.put(NormalExcelConstants.CLASS, CbsTechologyAgreeReportEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("技术支持完工单列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsTechologyAgreeReports);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsTechologyAgreeReportEntity cbsTechologyAgreeReport, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "技术支持完工单");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsTechologyAgreeReportEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsTechologyAgreeReportEntity> listCbsTechologyAgreeReportEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsTechologyAgreeReportEntity.class, params);
                for (CbsTechologyAgreeReportEntity cbsTechologyAgreeReport : listCbsTechologyAgreeReportEntitys) {
                    cbsTechologyAgreeReportService.save(cbsTechologyAgreeReport);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }


    /*
     * 技术支持暂存
     * */
    @RequestMapping(params = "ZCTechnologyAgree")
    @ResponseBody
    public AjaxJson ZCTechnologyAgree(HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            j = cbsTechologyAgreeReportService.ZCTechnologyAgree(request);
        } catch (Exception e) {
            j.setMsg("提交失败");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }


    @RequestMapping(params = "getEqTypes")
    @ResponseBody
    public List<ComboTree> getEsTypesTreeForIrReport() {
        //"typeDesc","放映机"
        List<ZyEquipmentTypeEntity> territoryList = systemService.findByQueryString("from ZyEquipmentTypeEntity where typeDesc = '放映机' ");
        List<ComboTree> comboTrees = new ArrayList<ComboTree>();
        ComboTreeModel comboTreeModel = new ComboTreeModel("id", "typeDesc", "childEquipmentTypes");
        comboTrees = systemService.comboTree(territoryList, comboTreeModel, null, true);
        return comboTrees;
    }


    @RequestMapping(params = "getTypes")
    @ResponseBody
    public AjaxJson getTypes(HttpServletRequest request) throws Exception {
        AjaxJson j = new AjaxJson();
        if (StringUtil.isNotEmpty(request.getParameter("eqType"))) {
            ZyEquipmentTypeEntity type = systemService.get(ZyEquipmentTypeEntity.class, request.getParameter("eqType"));
            List<ZyEquipmentTypeEntity> childEquipmentTypes = type.getChildEquipmentTypes();

            j.setObj(childEquipmentTypes);
        }
        return j;
    }


    /*
     * 技术支持提交
     * */
    @RequestMapping(params = "subTechnologyAgree")
    @ResponseBody
    public AjaxJson subTechnologyAgree(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = cbsTechologyAgreeReportService.subTechnologyAgree(request);
        } catch (Exception e) {
            j.setMsg("提交失败");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }


    /**
     * 上传附件功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "fileUploadView")
    public AjaxJson fileUploadView(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> attributes = new HashMap<String, Object>();
        String cbsServiceId = oConvertUtils.getString(request.getParameter("serviceId"));
        String businessType = request.getParameter("businessType");
        if (cbsServiceId != null && cbsServiceId != "") {
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            if (StringUtil.isNotEmpty(cbsServiceId)) {
                ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
                zyfileLog.setBusinessKey(cbsServiceId);
                zyfileLog.setFilePath(fileBean.getSavePath());
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setBusinessType("J");
                zyfileLog.setFileType("wgd");
                systemService.save(zyfileLog);
//
            }
            String id = null;
            Map<String, Object> fileLogMap = systemService.findOneForJdbc("SELECT t.id FROM zy_file_log t where  t.business_key = '" + cbsServiceId + "' and old_file_name = '" + fileBean.getFileRealName() + "'order by t.create_date desc limit 1 ");
            if (fileLogMap != null) {
                id = fileLogMap.get("id").toString();
            }
            attributes.put("name", fileBean.getFileRealName());
            attributes.put("id", id);
            try {
            } catch (Exception e) {
                e.printStackTrace();
            }
            j.setAttributes(attributes);
        }
        return j;
    }

    /**
     * 删除上传的文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String id = oConvertUtils.getString(request.getParameter("id"));
            if (id != null && id != "") {
                systemService.deleteEntityById(ZyFileLogEntity.class, id);
                j.setMsg("文件删除成功");
                j.setSuccess(true);
            }
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping(params = "getImgFile")
    @ResponseBody
    public AjaxJson getImgFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String businessKey = request.getParameter("businessKey");
        List<Object[]> files = systemService.findListbySql("select id from zy_file_log where business_type='J' and business_key='" + businessKey + "' ORDER BY create_date desc;");
        j.setObj(files);
        return j;
    }


}
